﻿using UnityEngine;
using System.Collections;
using System;
using System.Linq;
using System.Text;
using System.IO;
using System.Collections.Generic;
using System.Reflection;

public class CSVLoader
{
    public static string[][] LoadFile(string strFileName, char splitter = '\t')
    {
        TextAsset textAsset = Resources.Load(strFileName, typeof(TextAsset)) as TextAsset;
        if (textAsset == null)
        {
            Debug.LogError("ERR! file is not exsit. " + strFileName);
            return null;
        }

        string[] lineArray = textAsset.text.Split("\r"[0]);

        int nLength = lineArray.Length;

        //去掉最后一行是空行
        lineArray[nLength - 1] = lineArray[nLength - 1].Replace("\n", "");
        if (lineArray[nLength - 1].Length == 0)
        {
            nLength = lineArray.Length - 1;
        }

        string[][] array = new string[nLength][];
        for (int i = 0; i < nLength; i++)
        {
            lineArray[i] = lineArray[i].Replace("\n", "");
			array[i] = lineArray[i].Split(splitter);
        }
        return array;
    }

    public static List<T> LoadFile<T>(string strFileName, char splitter = ',')
    {
        TextAsset textAsset = Resources.Load(strFileName, typeof(TextAsset)) as TextAsset;
        //string data = HDParseJsonFile.ReadFileToData(strFileName);
        if (textAsset == null)
        {
            Debug.LogError("ERR! file is not exsit. " + strFileName);
            return null;
        }
        string[] lineArray = textAsset.text.Split("\r"[0]);
        
        //去掉最后一行是空行
        int nLength = lineArray.Length;
        lineArray[nLength - 1] = lineArray[nLength - 1].Replace("\n", "");
        if (lineArray[nLength - 1].Length == 0)
        {
            nLength = lineArray.Length - 1;
        }

        Type type = typeof(T);        
        List<T> list = new List<T>();
        string[][] array = new string[nLength][];

        for (int i = 0; i < nLength; i++)
        {
            lineArray[i] = lineArray[i].Replace("\n", "");
            array[i] = DoSplit(lineArray[i], splitter).ToArray();//lineArray[i].Split(splitter);            
            if (i == 0)
            {
                continue;
            }

            T t = (T)Activator.CreateInstance(typeof(T));
            for (int j = 0; j < array[i].Length; j++)
            {
                FieldInfo fieldInfo = type.GetField(array[0][j]);
                //Debug.Log(fieldInfo.Name + " " + fieldInfo.FieldType + ":" + array[i][j] + "=== " + i + " " + j);
                if (fieldInfo.FieldType == typeof(string))
                {
                    fieldInfo.SetValue(t, array[i][j]);
                    continue;  
                }

				if (fieldInfo.FieldType == typeof(int) || fieldInfo.FieldType == typeof(double) ||
				    fieldInfo.FieldType == typeof(float))
				{
                	if (array[i][j] == "")
                	{
                   		array[i][j] = "0";
                	}
				}

				HD.Reflection.SetFieldValue(t, fieldInfo, array[i][j]);
            }
            list.Add(t);
        }
        return list;
    }

    public static List<string> DoSplit(string line, char splitter = ',')
    {
        List<string> list = new List<string>();
        string tempString = "";
        bool bOpen = false;
        for (int i = 0; i < line.Length; i++)
        {
            if (bOpen == false && line[i] == splitter)
            {
                list.Add(tempString);                
                tempString = "";
                continue;
            }
            
            if (line[i] == '"')
            {
                bOpen = !bOpen;
            }       
            else
            {
                tempString += line[i];
            }
        }

		if (tempString.Length > 0)
			list.Add(tempString);
        	
        return list;
    }

    public static string GetDataByRowAndCol(string[][] array, int nRow, int nCol)
    {
        if (array.Length <= 0 || nRow >= array.Length)
            return "";
        if (nCol >= array[0].Length)
            return "";

        return array[nRow][nCol];
    }

    // Id 为第一行的 编号
    public static string GetDataByIdAndName(string[][] array, int nId, string strName)
    {
        if (array.Length <= 0)
            return "";

        int nRow = array.Length;
        int nCol = array[0].Length;
        for (int i = 1; i < nRow; ++i)
        {
            string strId = string.Format("{0}", nId);
            if (array[i][0] == strId)
            {
                for (int j = 0; j < nCol; ++j)
                {
                    if (array[0][j] == strName)
                    {
                        return array[i][j];
                    }
                }
            }
        }
        return "";
    }

    // Index为行
    public static string GetDataByIndexAndName(string[][] array, int nIndex, string strName)
    { 
        string strValue = "0";
        if (array.Length <= 0)
        {
            return strValue;
        }
        
        for (int j = 0; j < array[0].Length; ++j)
        {
            if (array[0][j] == strName)
            {
                //Debug.Log(array[nIndex][j] + ":" + nIndex + ":" + strName);
                strValue = array[nIndex][j];
                if (strValue == "")
                {
                    strValue = "0";
                }                
                return strValue;
            }
        }
        return strValue;
    }    
    public static int GetNumberDataByIdAndName(string[][] array, int nId, string strName)
    {
        int nResult = 0;
        string strNumber = GetDataByIdAndName(array, nId, strName);
        if (!string.IsNullOrEmpty(strNumber))
        {
            nResult = System.Convert.ToInt32(strNumber);
        }
        
        return nResult;
    }
}
